package com.ncmem.up6.database;

import com.ncmem.up6.model.FileInf;
import com.ncmem.up6.sql.SqlExec;
import com.ncmem.up6.sql.SqlParam;
import com.ncmem.up6.sql.SqlWhereMerge;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DbFolderMongodb extends DbFolder{

    /**
     * 取目录信息（可能是根目录，也可能是子目录）
     * @param id
     * @return
     */
    public FileInf read(String id) {
        FileInf folder = new FileInf();
        return  folder;
    }

    /**
     * 取同名目录信息
     * @param pathRel
     * @param pid
     * @return
     */
    public FileInf read(String pathRel, String pid, String id) {
        SqlExec se = new SqlExec();
        String sql = String.format("select f_id,f_pid,f_pidRoot,f_pathSvr,f_pathRel from up6_files where f_pid='%s' and f_pathRel='%s' and f_deleted=0 and f_id!='%s' union select f_id,f_pid,f_pidRoot,f_pathSvr,f_pathRel from up6_folders where f_pid='%s' and f_pathRel='%s' and f_deleted=0 and f_id!='%s'", pid,pathRel,id,pid,pathRel,id);
        JSONArray data = se.exec("up6_files", sql, "f_id,f_pid,f_pidRoot,f_pathSvr,f_pathRel","");
        if(data.size() < 1) return null;

        JSONObject o = (JSONObject)data.get(0);

        FileInf file = new FileInf();
        file.id = o.getString("f_id").trim();
        file.pid = o.getString("f_pid").trim();
        file.pidRoot = o.getString("f_pidRoot").trim();
        file.pathSvr = o.getString("f_pathSvr").trim();
        file.pathRel = o.getString("f_pathRel").trim();
        return file;
    }

    public Boolean exist_same_file(String name,String pid)
    {
        SqlWhereMerge swm = new SqlWhereMerge();
        swm.equal("f_nameLoc", name.trim());
        swm.equal("f_pid", pid.trim());
        swm.equal("f_deleted", 0);

        String sql = String.format("select f_id from up6_files where %s ", swm.to_sql());

        SqlExec se = new SqlExec();
        JSONArray arr = se.exec("up6_files", sql, "f_id", "");
        return arr.size() > 0;
    }

    public Boolean rename_file_check(String newName,String pid)
    {
        SqlExec se = new SqlExec();
        JSONArray res = se.select("up6_files"
                , "f_id"
                ,new SqlParam[] {
                        new SqlParam("f_nameLoc",newName)
                        ,new SqlParam("f_pid",pid)
                },"");
        return res.size() > 0;
    }

    public Boolean rename_folder_check(String newName, String pid)
    {
        SqlExec se = new SqlExec();
        JSONArray res = se.select("up6_folders"
                , "f_id"
                , new SqlParam[] {
                        new SqlParam("f_nameLoc",newName)
                        ,new SqlParam("f_pid",pid)
                },"");
        return res.size() > 0;
    }

    public void rename_file(String name,String id) {
        SqlExec se = new SqlExec();
        se.update("up6_files"
                , new SqlParam[] { new SqlParam("f_nameLoc", name) }
                , new SqlParam[] { new SqlParam("f_id", id) });
    }

    public void rename_folder(String name, String id, String pid) {
        SqlExec se = new SqlExec();
        se.update("up6_folders"
                , new SqlParam[] { new SqlParam("f_nameLoc", name) }
                , new SqlParam[] { new SqlParam("f_id", id) });
    }

    public void del(String id,int uid) {
        SqlExec se = new SqlExec();
        se.update("up6_files",
                new SqlParam[] {
                        new SqlParam("f_deleted", true)
                },
                new SqlParam[] {
                        new SqlParam("f_id", id),
                        new SqlParam("f_uid", uid)
                });
        se.update("up6_folders",
                new SqlParam[] {
                        new SqlParam("f_deleted", true)
                },
                new SqlParam[] {
                        new SqlParam("f_id", id),
                        new SqlParam("f_uid", uid)
                });
    }


    public boolean existSameFolder(String name,String pid)
    {
        SqlExec se = new SqlExec();

        //子目录
        if(!StringUtils.isEmpty(pid))
        {
            return se.count("up6_folders",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }//根目录
        else
        {
            return se.count("up6_files",new SqlParam[] {
                    new SqlParam("f_nameLoc",name),
                    new SqlParam("f_pid",pid),
                    new SqlParam("f_deleted",false)
            })>0;
        }
    }

    /**
     * 更新子文件路径
     * @param pathRelOld
     * @param pathRelNew
     */
    public void updatePathRel(String pathRelOld,String pathRelNew)
    {
        //更新子文件路径
        String sql = String.format("update up6_folders set f_pathRel=REPLACE(f_pathRel,'%s/','%s/') where CHARINDEX('%s/',f_pathRel)>0",
                pathRelOld,
                pathRelNew,
                pathRelOld
        );

        SqlExec se = new SqlExec();
        se.exec(sql);
    }

    //批量添加
    public void addBatch(List<FileInf> arr) throws SQLException
    {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into up6_folders (");
        sb.append(" f_id");//1
        sb.append(",f_pid");//2
        sb.append(",f_pidRoot");//3
        sb.append(",f_nameLoc");//4
        sb.append(",f_uid");//5
        sb.append(",f_pathLoc");//6
        sb.append(",f_pathSvr");//7
        sb.append(",f_pathRel");//8
        sb.append(",f_complete");//9
        sb.append(") values(");//
        sb.append(" ?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(",?");
        sb.append(")");

        DbHelper db = new DbHelper();
        Connection con = db.GetCon();
        PreparedStatement cmd = con.prepareStatement(sb.toString());
        cmd.setString(1, "");//id
        cmd.setString(2, "");//pid
        cmd.setString(3, "");//pidRoot
        cmd.setString(4, "");//nameLoc
        cmd.setInt(5, 0);//f_uid
        cmd.setString(6, "");//pathLoc
        cmd.setString(7, "");//pathSvr
        cmd.setString(8, "");//pathRel
        cmd.setBoolean(9, true);//complete

        for(int i=0 , l = arr.size() ; i < l ; ++i)
        {
            FileInf f = (FileInf)arr.get(i);

            cmd.setString(1, f.id);//id
            cmd.setString(2, f.pid);//pid
            cmd.setString(3, f.pidRoot);//pidRoot
            cmd.setString(4, f.nameSvr);//name
            cmd.setInt(5, f.uid);//f_uid
            cmd.setString(6, f.pathLoc);//pathLoc
            cmd.setString(7, f.pathSvr);//pathSvr
            cmd.setString(8, f.pathRel);//pathRel
            cmd.setBoolean(9, true);//complete
            cmd.executeUpdate();
        }
        cmd.close();
        con.close();
    }
}
